package org.springleaf.security.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springleaf.core.json.IJsonObject;
import org.springleaf.utils.Obj2MapUtils;

/**
 * 登录用户
 * @author leaf
 */
@Entity
@Inheritance(strategy = InheritanceType.JOINED)// join的方式来继承
public class User implements IJsonObject,UserDetails{
	
	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	private String username;
	private String password;
	private String role;
	private boolean enabled = true;
	
	private boolean accountNonExpired = true;
	private boolean accountNonLocked = true;
	private boolean credentialsNonExpired = true;

	@Override
	public Collection<GrantedAuthority> getAuthorities() {
		List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
		if(role != null){
			String [] array = role.split(",");
			if(array != null){
				for(String s : array){
					list.add(new GrantedAuthorityImpl(s));
				}
			}
		}
		return list;
	}

	
	public Object toJSonObject() {
		return Obj2MapUtils.toMapExcep(this,new String[]{});
	}
	
	

	public Long getId() {
		return id;
	}


	public void setId(Long id) {
		this.id = id;
	}


	@Override
	public String getPassword() {
		return this.password;
	}

	@Override
	public String getUsername() {
		return this.username;
	}

	
	@Override
	public boolean isAccountNonExpired() {
		return this.accountNonExpired;
	}

	@Override
	public boolean isAccountNonLocked() {
		return this.accountNonLocked;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return this.credentialsNonExpired;
	}

	@Override
	public boolean isEnabled() {
		return this.enabled;
	}

	public String getRole() {
		return role;
	}

	public void setUsername(String username) {
		this.username = username;
		
	}

	public void setPassword(String password) {
		this.password = password;
		
	}

	public void setRole(String role) {
		this.role = role;
		
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
		
	}
	
}
